<?php


namespace api\controllers;


use api\components\BaseController;
use common\helpers\commonApi;
use common\models\Cart;
use common\models\Goods;
use common\models\GoodsSpec;
use common\models\Order;
use Yii;

/**
 * 购物车控制器
 * Class CartController
 * @package api\modules\v1\controllers
 */
class CartController extends BaseController
{

    /**
     * 获取购物车列表
     * @return \api\components\B5Response|false
     */
    public function actionList()
    {
        $userid = self::$userid;
        $data = Cart::find()
            ->where([Cart::tableName() . '.user_id' => $userid])
            ->select([
                Cart::tableName() . '.id as cart_id',
                Cart::tableName() . '.good_num as num',
                Cart::tableName() . '.spec_id',
                Cart::tableName() . '.good_id as g_id',
                Cart::tableName() . '.selected',
            ])
            ->asArray()
            ->all();
        $total_amount = 0;
        if (!$data){
            return commonApi::message('成功',true,['data'=>[],'total_amount'=>$total_amount]);
        }
        $amount = Order::calculate($data,$userid,1);
        $goods_spec = array_column($amount['data']['goods_spec'],null,'mark');
        foreach ($data as $k=>&$datum){
            $mark = $datum['g_id'].'_'.$datum['spec_id'];
            if (empty($goods_spec[$mark])){
                unset($data[$k]);
            }else{
                $datum['price'] = $goods_spec[$mark]['total_pay_price'];
                $datum['spec_name'] = $goods_spec[$mark]['spec_name'];
                $datum['goods_name'] = $goods_spec[$mark]['good_name'];
                $datum['stock'] = $goods_spec[$mark]['stock'];
                $datum['main_img'] = commonApi::getDomain($goods_spec[$mark]['main_img']);
            }
            if ($datum['selected']){
                $total_amount += $datum['price'];
            }
        }
        return commonApi::message('成功',true,['data'=>array_values($data),'total_amount'=>$total_amount]);
    }

    /**
     * 加入购物车
     * @return \api\components\B5Response|false
     */
    public function actionJoin()
    {
        $userid = self::$userid;
        $params = Yii::$app->request->post();
        $goods_id = $params['good_id']??'';
        $spec_id = $params['spec_id']??'';
        $good_num = $params['num']??1;
        if (!$goods_id){
            return commonApi::message('请选择要加入购物车的商品',false);
        }
        if (!$spec_id){
            return commonApi::message('请选择要加入购物车商品规格',false);
        }
        if (!$good_num){
            return commonApi::message('请选择要加入购物车商品数量',false);
        }
        if (!preg_match("/^[1-9][0-9]*$/" ,$good_num)){
            return commonApi::message('商品数量错误',false);
        }
        $good = Goods::find()->where(['id'=>$goods_id,'status'=>1,'delete'=>0])->asArray()->one();
        if (!$good){
            return commonApi::message('商品已下架',false);
        }
        $goodsspec = GoodsSpec::find()->where(['id'=>$spec_id,'g_id'=>$goods_id])->exists();
        if (!$goodsspec){
            return commonApi::message('商品规格不存在',false);
        }
        $model = Cart::find()->where(['user_id'=>$userid,'good_id'=>$goods_id,'spec_id'=>$spec_id])->one();
        if ($model){
            $model->good_num += $good_num;
        }else{
            $model = new Cart();
            $model->good_num = $good_num;
        }
        $model->user_id = $userid;
        $model->good_id = $goods_id;
        $model->spec_id = $spec_id;
        $model->selected = 1;
        if ($model->save()){
            return commonApi::message('加入成功');
        }
        return commonApi::message(commonApi::getModelError($model),false);
    }

    /**
     * 购物车选中或取消
     * @return \api\components\B5Response|false
     */
    public function actionSelect()
    {
        $userid = self::$userid;
        $params = Yii::$app->request->post();
        $cart_id = $params['cart_id']??'';
        if (!$cart_id){
            return commonApi::message('请选择要选中的商品',false);
        }
        $model = Cart::find()->where(['user_id'=>$userid,'id'=>$cart_id])->one();
        if (!$model){
            return commonApi::message('该商品不存在购物车中',false);
        }
        $model->selected = $model->selected==1?0:1;
        if ($model->save()){
            return commonApi::message('操作成功');
        }
        return commonApi::message(commonApi::getModelError($model),false);
    }

    /**
     * 购物车全选或全取消
     * @return \api\components\B5Response|false
     */
    public function actionAllSelect()
    {
        $userid = self::$userid;
        $params = Yii::$app->request->post();
        $selected = $params['selected']??0;
        $res = Cart::updateAll(['selected'=>$selected],['user_id'=>$userid]);
        $msg = $selected==1?'全选':'取消';
        if ($res){
            return commonApi::message($msg.'成功');
        }
        return commonApi::message($msg.'失败',false);
    }

    /**
     * 购物车商品加减
     * @return \api\components\B5Response|false
     */
    public function actionAddSubtract()
    {
        $params = Yii::$app->request->post();
        $userid = self::$userid;
        $type = $params['type']??1;
        $cart_id = $params['cart_id']??'';
        $num = $params['num']??1;
        if (!$cart_id){
            return commonApi::message('请选择购物车商品',false);
        }
        if (!preg_match("/^[1-9][0-9]*$/" ,$num)){
            return commonApi::message('商品数量错误',false);
        }
        $model = Cart::find()->where(['user_id'=>$userid,'id'=>$cart_id])->one();
        if (!$model){
            return commonApi::message('该商品不存在购物车中',false);
        }
        if (!(int)$type){
            if ($model->good_num<=1){
                return commonApi::message('最少购买1件哦',false);
            }
        }
        if ((int)$type==1){
            $model->good_num += $num;
        }else{
            $model->good_num -= $num;
        }
        if ($model->save()){
            return commonApi::message('操作成功');
        }
        return commonApi::message(commonApi::getModelError($model),false);
    }

    /**
     * 购物车下单
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function actionBuy()
    {
        $params = Yii::$app->request->post();
        $userid = self::$userid;
        $cart_ids = $params['cart_ids']??'';
        $address_id = $params['address_id']??'';
        if (!$cart_ids){
            return commonApi::message('请选择商品',false);
        }
        $arr = explode(',',$cart_ids);
        $data = Cart::find()->select(['good_id as g_id','good_num as num','spec_id'])->where(['id'=>$arr,'user_id'=>$userid])->asArray()->all();
        if (count($arr)!==count($data)){
            return commonApi::message('数据错误',false);
        }
        if (!$address_id){
            return commonApi::message('请选择收货地址！',false);
        }
        $address = [];
        $userid = self::$userid;
        $order = new Order();
        $data = $order->calculate($data,$userid,1);
        if (!$data['success']){
            return $data;
        }
        if (!$data['data']['goods_spec']){
            return commonApi::message('暂无可购买',false);
        }
        //微信订单号
        $party_order = Order::makePartyOrder();
        //系统订单号
        $order_sn = Order::makeOrderid();
        $desc = '购买商品-'.$order_sn;
        $pay = $order->getPayresponse($data['data']['goods_data']['pay_amount'],$userid,$party_order,$desc);
        if (!$pay['success']){
            return $pay;
        }
        $saveRes = $order->saveOrder($pay['data'],$data['data'],$userid,$order_sn,$party_order,$address);
        if (!$saveRes['success']){
            return $saveRes;
        }
        return commonApi::message($saveRes['msg'],true,$pay['data']);
    }
}